<script setup lang="ts">
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { updateRules } from "../utils/rule";
import type { FormInstance } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { register } from "@/api/authApi";
import { getTopMenu, initRouter } from "@/router/utils";
import { useRouter } from "vue-router";
import { setToken } from "@/utils/auth";

const router = useRouter();
const checked = ref(false);
const loading = ref(false);
const ruleForm = reactive({
  username: "",
  password: "",
  confirmPassword: ""
});
const ruleFormRef = ref<FormInstance>();
const confirmPasswordRule = [
  {
    validator: (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (ruleForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    trigger: "blur"
  }
];
const onLogin = async () => {
  try {
    await initRouter();
    router.push(getTopMenu(true).path);
  } catch (e) {
    message("登录失败", { type: "error" });
  }
};

const onUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (checked.value) {
        loading.value = true;
        try {
          const res = await register(ruleForm);
          loading.value = false;
          setToken(res.data);
          onLogin();
          message("注册成功，自动登录中...", {
            type: "success"
          });
        } catch (e) {
          console.log(e);
        } finally {
          loading.value = false;
        }
      } else {
        message("请勾选用户协议", {
          type: "warning"
        });
      }
    }
  });
};
const emits = defineEmits(["back"]);
function onBack() {
  emits("back");
}
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="updateRules"
    size="large"
  >
    <Motion>
      <el-form-item
        :rules="[
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          }
        ]"
        prop="username"
      >
        <el-input
          v-model="ruleForm.username"
          clearable
          placeholder="账号"
          :prefix-icon="useRenderIcon(User)"
          class="w-full"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="200">
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          clearable
          show-password
          placeholder="密码"
          :prefix-icon="useRenderIcon(Lock)"
          class="w-full"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="250">
      <el-form-item :rules="confirmPasswordRule" prop="confirmPassword">
        <el-input
          v-model="ruleForm.confirmPassword"
          clearable
          show-password
          placeholder="确认密码"
          :prefix-icon="useRenderIcon(Lock)"
          class="w-full"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="300">
      <el-form-item>
        <el-checkbox v-model="checked"> 我已仔细阅读并接受 </el-checkbox>
        <el-button link type="primary"> 《隐私协议》 </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="350">
      <el-form-item>
        <el-button
          class="w-full"
          size="default"
          type="primary"
          :loading="loading"
          @click="onUpdate(ruleFormRef)"
        >
          确定
        </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="400">
      <el-form-item>
        <el-button class="w-full" size="default" @click="onBack">
          返回
        </el-button>
      </el-form-item>
    </Motion>
  </el-form>
</template>
